package org.jix.gbook.oss.biz.strategy.impl;

import com.aliyun.oss.OSS;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jix.gbook.oss.biz.config.AliyunOSSProperties;
import org.jix.gbook.oss.biz.strategy.FileStrategy;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * @author stark
 * @date 2025/6/8 12:52
 * @description
 **/
@Slf4j
public class AliyunOSSFileStrategyImpl implements FileStrategy {

    @Resource
    private AliyunOSSProperties aliyunOSSProperties;
    @Resource
    private OSS ossClient;

    @Override
    @SneakyThrows
    public String uploadFile(MultipartFile file, String bucketName) {
        log.info("## 上传文件至 阿里云 ...");

        //判空
        if (file == null || file.getSize() == 0){
            log.error("==> 上传文件异常：文件大小为空 ...");
            throw new RuntimeException("文件大小不能为空");
        }
        //文件原始名
        String originalFilename = file.getOriginalFilename();
        //生成对象存储的名称
        String key = UUID.randomUUID().toString().replace("-", "");
        //获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接
        String objectName = String.format("%s%s", key, suffix);

        log.info("==> 开始上传文件至阿里云 OSS, ObjectName: {}", objectName);

        //上传文件到阿里云OSS
        ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(file.getInputStream().readAllBytes()));

        //返回访问链接
        // 返回文件的访问链接
        String url = String.format("https://%s.%s/%s", bucketName, aliyunOSSProperties.getEndpoint(), objectName);
        log.info("==> 上传文件至阿里云 OSS 成功，访问路径: {}", url);
        return url;
    }
}
